<template>
  <div class="learning-plan-container">
    <div class="page-header">
      <h1>学习计划</h1>
      <p>制定个性化学习计划，提高学习效率</p>
    </div>
    
    <div class="plan-content">
      <div class="plan-sidebar">
        <div class="sidebar-header">
          <h3>我的计划</h3>
          <el-button type="primary" size="small" @click="showCreatePlanDialog">
            <el-icon><Plus /></el-icon> 新建计划
          </el-button>
        </div>
        
        <div class="plan-list">
          <div 
            v-for="(plan, index) in plans" 
            :key="index"
            :class="['plan-item', { active: currentPlanIndex === index }]"
            @click="selectPlan(index)"
          >
            <div class="plan-item-title">{{ plan.title }}</div>
            <div class="plan-item-meta">
              <span class="plan-date">{{ plan.startDate }} - {{ plan.endDate }}</span>
              <el-progress 
                :percentage="calculateProgress(plan)" 
                :status="plan.completed ? 'success' : ''"
                :stroke-width="5"
                class="plan-progress"
              ></el-progress>
            </div>
          </div>
        </div>
      </div>
      
      <div class="plan-main" v-if="currentPlan">
        <div class="plan-header">
          <div>
            <h2>{{ currentPlan.title }}</h2>
            <div class="plan-meta">
              <span class="plan-date">{{ currentPlan.startDate }} - {{ currentPlan.endDate }}</span>
              <el-tag :type="currentPlan.completed ? 'success' : 'primary'" size="small">
                {{ currentPlan.completed ? '已完成' : '进行中' }}
              </el-tag>
            </div>
          </div>
          <div class="plan-actions">
            <el-button type="primary" plain size="small" @click="editPlan">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="danger" plain size="small" @click="confirmDeletePlan">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </div>
        </div>
        
        <div class="plan-description">
          <p>{{ currentPlan.description }}</p>
        </div>
        
        <div class="plan-tasks">
          <h3>任务列表</h3>
          <el-table :data="currentPlan.tasks" style="width: 100%">
            <el-table-column prop="title" label="任务名称" min-width="180"></el-table-column>
            <el-table-column prop="subject" label="学科" width="100"></el-table-column>
            <el-table-column prop="deadline" label="截止日期" width="120"></el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.completed ? 'success' : 'info'">
                  {{ scope.row.completed ? '已完成' : '未完成' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button 
                  :type="scope.row.completed ? 'info' : 'success'" 
                  size="small"
                  @click="toggleTaskStatus(scope.$index)"
                >
                  {{ scope.row.completed ? '标为未完成' : '标为完成' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="add-task">
            <el-button type="primary" plain @click="showAddTaskDialog">
              <el-icon><Plus /></el-icon> 添加任务
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="empty-plan" v-else>
        <el-empty description="请选择或创建一个学习计划"></el-empty>
      </div>
    </div>
    
    <!-- 创建计划对话框 -->
    <el-dialog
      v-model="createPlanDialogVisible"
      :title="isEditing ? '编辑学习计划' : '创建学习计划'"
      width="500px"
    >
      <el-form :model="planForm" label-width="100px" :rules="planRules" ref="planFormRef">
        <el-form-item label="计划名称" prop="title">
          <el-input v-model="planForm.title" placeholder="请输入计划名称"></el-input>
        </el-form-item>
        <el-form-item label="计划时间" prop="dateRange">
          <el-date-picker
            v-model="planForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="计划描述" prop="description">
          <el-input
            v-model="planForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入计划描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createPlanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPlanForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加任务对话框 -->
    <el-dialog
      v-model="addTaskDialogVisible"
      title="添加任务"
      width="500px"
    >
      <el-form :model="taskForm" label-width="100px" :rules="taskRules" ref="taskFormRef">
        <el-form-item label="任务名称" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="学科" prop="subject">
          <el-select v-model="taskForm.subject" placeholder="请选择学科" style="width: 100%">
            <el-option label="数学" value="数学"></el-option>
            <el-option label="语文" value="语文"></el-option>
            <el-option label="英语" value="英语"></el-option>
            <el-option label="物理" value="物理"></el-option>
            <el-option label="化学" value="化学"></el-option>
            <el-option label="生物" value="生物"></el-option>
            <el-option label="历史" value="历史"></el-option>
            <el-option label="地理" value="地理"></el-option>
            <el-option label="政治" value="政治"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker
            v-model="taskForm.deadline"
            type="date"
            placeholder="选择截止日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTaskForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteConfirmVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除计划"{{ currentPlan?.title }}"吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deletePlan">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

const store = useStore();
const currentPlanIndex = ref(null);
const createPlanDialogVisible = ref(false);
const addTaskDialogVisible = ref(false);
const deleteConfirmVisible = ref(false);
const isEditing = ref(false);
const planFormRef = ref(null);
const taskFormRef = ref(null);

// 计划表单
const planForm = reactive({
  title: '',
  dateRange: [],
  description: ''
});

// 任务表单
const taskForm = reactive({
  title: '',
  subject: '',
  deadline: ''
});

// 表单验证规则
const planRules = {
  title: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  dateRange: [{ required: true, message: '请选择计划时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入计划描述', trigger: 'blur' }]
};

const taskRules = {
  title: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  subject: [{ required: true, message: '请选择学科', trigger: 'change' }],
  deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }]
};

// 从 store 获取学习计划数据
const plans = computed(() => {
  return store.state.home.learningPlans || [];
});

// 当前选中的计划
const currentPlan = computed(() => {
  if (currentPlanIndex.value === null) return null;
  return plans.value[currentPlanIndex.value];
});

// 计算计划完成进度
const calculateProgress = (plan) => {
  if (!plan.tasks || plan.tasks.length === 0) return 0;
  const completedTasks = plan.tasks.filter(task => task.completed).length;
  return Math.round((completedTasks / plan.tasks.length) * 100);
};

// 选择计划
const selectPlan = (index) => {
  currentPlanIndex.value = index;
};

// 显示创建计划对话框
const showCreatePlanDialog = () => {
  isEditing.value = false;
  planForm.title = '';
  planForm.dateRange = [];
  planForm.description = '';
  createPlanDialogVisible.value = true;
};

// 编辑计划
const editPlan = () => {
  if (!currentPlan.value) return;
  
  isEditing.value = true;
  planForm.title = currentPlan.value.title;
  planForm.dateRange = [new Date(currentPlan.value.startDate), new Date(currentPlan.value.endDate)];
  planForm.description = currentPlan.value.description;
  createPlanDialogVisible.value = true;
};

// 提交计划表单
const submitPlanForm = async () => {
  if (!planFormRef.value) return;
  
  await planFormRef.value.validate((valid) => {
    if (valid) {
      const startDate = planForm.dateRange[0].toLocaleDateString();
      const endDate = planForm.dateRange[1].toLocaleDateString();
      
      if (isEditing.value) {
        // 更新计划
        store.dispatch('home/updateLearningPlan', {
          index: currentPlanIndex.value,
          plan: {
            ...currentPlan.value,
            title: planForm.title,
            startDate,
            endDate,
            description: planForm.description
          }
        });
        ElMessage.success('计划已更新');
      } else {
        // 创建新计划
        const newPlan = {
          id: Date.now(),
          title: planForm.title,
          startDate,
          endDate,
          description: planForm.description,
          completed: false,
          tasks: []
        };
        store.dispatch('home/addLearningPlan', newPlan);
        currentPlanIndex.value = plans.value.length - 1;
        ElMessage.success('计划已创建');
      }
      
      createPlanDialogVisible.value = false;
    }
  });
};

// 显示添加任务对话框
const showAddTaskDialog = () => {
  taskForm.title = '';
  taskForm.subject = '';
  taskForm.deadline = '';
  addTaskDialogVisible.value = true;
};

// 提交任务表单
const submitTaskForm = async () => {
  if (!taskFormRef.value) return;
  
  await taskFormRef.value.validate((valid) => {
    if (valid) {
      const newTask = {
        id: Date.now(),
        title: taskForm.title,
        subject: taskForm.subject,
        deadline: taskForm.deadline.toLocaleDateString(),
        completed: false
      };
      
      store.dispatch('home/addTaskToPlan', {
        planIndex: currentPlanIndex.value,
        task: newTask
      });
      
      addTaskDialogVisible.value = false;
      ElMessage.success('任务已添加');
    }
  });
};

// 切换任务状态
const toggleTaskStatus = (taskIndex) => {
  store.dispatch('home/toggleTaskStatus', {
    planIndex: currentPlanIndex.value,
    taskIndex
  });
};

// 确认删除计划
const confirmDeletePlan = () => {
  deleteConfirmVisible.value = true;
};

// 删除计划
const deletePlan = () => {
  store.dispatch('home/deleteLearningPlan', currentPlanIndex.value);
  deleteConfirmVisible.value = false;
  currentPlanIndex.value = null;
  ElMessage.success('计划已删除');
};
</script>

<style lang="scss" scoped>
.learning-plan-container {
  padding: 20px;
  max-width: 90%;
  margin: 0 auto;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 10px;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
    }
  }
  
  .plan-content {
    display: flex;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow: hidden;
    min-height: calc(100vh - 200px);
    
    .plan-sidebar {
      width: 280px;
      border-right: 1px solid #ebeef5;
      background-color: #f5f7fa;
      
      .sidebar-header {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ebeef5;
        
        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
      }
      
      .plan-list {
        .plan-item {
          padding: 15px;
          border-bottom: 1px solid #ebeef5;
          cursor: pointer;
          transition: background-color 0.3s;
          
          &:hover {
            background-color: #ecf5ff;
          }
          
          &.active {
            background-color: #ecf5ff;
          }
          
          .plan-item-title {
            font-weight: 500;
            margin-bottom: 8px;
            color: #303133;
          }
          
          .plan-item-meta {
            display: flex;
            flex-direction: column;
            
            .plan-date {
              font-size: 12px;
              color: #909399;
              margin-bottom: 8px;
            }
            
            .plan-progress {
              margin-top: 5px;
            }
          }
        }
      }
    }
    
    .plan-main {
      flex: 1;
      padding: 20px;
      
      .plan-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20px;
        
        h2 {
          margin: 0 0 10px;
          font-size: 20px;
          color: #303133;
        }
        
        .plan-meta {
          display: flex;
          align-items: center;
          
          .plan-date {
            margin-right: 10px;
            color: #606266;
            font-size: 14px;
          }
        }
      }
      
      .plan-description {
        background-color: #f5f7fa;
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 20px;
        
        p {
          margin: 0;
          color: #606266;
          line-height: 1.6;
        }
      }
      
      .plan-tasks {
        h3 {
          margin: 0 0 15px;
          font-size: 16px;
          color: #303133;
        }
        
        .add-task {
          margin-top: 15px;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
    
    .empty-plan {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

@media (max-width: 768px) {
  .plan-content {
    flex-direction: column;
    
    .plan-sidebar {
      width: 100%;
      border-right: none;
      border-bottom: 1px solid #ebeef5;
    }
  }
}
</style> 